package com.fafa.yygh.hosp.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.fafa.yygh.hosp.repository.DepartmentRepository;
import com.fafa.yygh.hosp.service.DepartmentService;
import com.fafa.yygh.model.hosp.Department;
import com.fafa.yygh.vo.hosp.DepartmentQueryVo;
import com.fafa.yygh.vo.hosp.DepartmentVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author Sire
 * @version 1.0
 * @date 2022-02-11 20:33
 */
@Service
@Slf4j
public class DepartmentServiceImpl implements DepartmentService {

    @Autowired
    private DepartmentRepository departmentRepository;

    /**
     * 上传科室信息
     *
     * @param paramMap
     */
    @Override
    public void save(Map<String, Object> paramMap) {
        // 先将map转换成字符串
        String s = JSONObject.toJSONString(paramMap);
        // 将其转成对象
        Department department = JSONObject.parseObject(s, Department.class);
        // 查看数据库中是否存在相关数据(通过医院编号和科室编号，注意Spring - Data的名命规范)
        Department targetDepartment =
                departmentRepository.getDepartmentByHoscodeAndDepcode(department.getHoscode(), department.getDepcode());
        if (null == targetDepartment) {
            // 添加操作
            department.setCreateTime(new Date());
            department.setUpdateTime(new Date());
            department.setIsDeleted(0);
            departmentRepository.save(department);
        } else {
            // 更新操作
            department.setUpdateTime(new Date());
            BeanUtils.copyProperties(department, targetDepartment, Department.class);
            departmentRepository.save(targetDepartment);
        }
    }

    /**
     * 查询科室信息（分页）
     *
     * @param page
     * @param limit
     * @param departmentQueryVo
     * @return
     */
    @Override
    public Page<Department> selectPage(Integer page, Integer limit, DepartmentQueryVo departmentQueryVo) {
        // 排序（按照创建时间进行降序）
        Sort sort = Sort.by(Sort.Direction.DESC, "createTime");
        // 分页
        Pageable pageable = PageRequest.of(page - 1, limit, sort);
        Department department = new Department();
        // 复制
        BeanUtils.copyProperties(departmentQueryVo, department);
        department.setIsDeleted(0);
        // 创建匹配器，即如何使用查询条件
        ExampleMatcher exampleMatcher = ExampleMatcher.matching()
                // 改变默认字符串匹配方式：模糊查询
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)
                // 忽略大小写
                .withIgnoreCase(true);
        // 查询条件
        Example<Department> example = Example.of(department, exampleMatcher);
        // 查询所有符合条件的结果（并进行分页）
        Page<Department> pages = departmentRepository.findAll(example, pageable);
        return pages;
    }

    /**
     * 删除科室（物理删除）
     *
     * @param hoscode
     * @param depcode
     */
    @Override
    public void removeDepartment(String hoscode, String depcode) {
        // 先获取相关对象
        Department department = departmentRepository.getDepartmentByHoscodeAndDepcode(hoscode, depcode);
        departmentRepository.deleteById(department.getId());
    }

    /**
     * 根据医院编号，查询医院所有科室列表
     *
     * @param hoscode
     * @return
     */
    @Override
    public List<DepartmentVo> findDeptTree(String hoscode) {
        // 创建list集合
        List<DepartmentVo> result = new ArrayList<>();
        // 根据医院编号，查询医院所有科室信息
        Department departmentQuery = new Department();
        departmentQuery.setHoscode(hoscode);
        Example<Department> example = Example.of(departmentQuery);
        // 所有科室列表
        List<Department> departmentList = departmentRepository.findAll(example);
        // 根据大科室编号 bigCode 分组，获取每个大科室里面下级子科室
        // 这里是根据 bigCode 进行的分组处理
        Map<String, List<Department>> departmentMap =
                departmentList.stream().collect(Collectors.groupingBy(Department::getBigcode));
        //遍历map集合 deparmentMap
        for (Map.Entry<String, List<Department>> entry : departmentMap.entrySet()) {
            // 大科室编号
            String bigCode = entry.getKey();
            // 大科室编号对应的全局数据
            List<Department> departmentList1 = entry.getValue();

            // 封装大科室
            DepartmentVo departmentVo = new DepartmentVo();
            // 大科室编号
            departmentVo.setDepcode(bigCode);
            // 大科室名字
            departmentVo.setDepname(departmentList1.get(0).getBigname());

            // 封装小科室
            List<DepartmentVo> children = new ArrayList<>();
            for (Department department : departmentList1) {
                DepartmentVo departmentVo1 = new DepartmentVo();
                departmentVo1.setDepname(department.getDepname());
                departmentVo1.setDepcode(department.getDepcode());
                //封装到list集合
                children.add(departmentVo1);
            }
            departmentVo.setChildren(children);

            result.add(departmentVo);
        }
        return result;
    }

    @Override
    public String getDepName(String hoscode, String depcode) {
        Department department = departmentRepository.getDepartmentByHoscodeAndDepcode(hoscode, depcode);
        if (null != department) {
            return department.getDepname();
        }
        return "";
    }

    /**
     * 获取部门
     * @param hoscode
     * @param depcode
     * @return
     */
    @Override
    public Department getDepartment(String hoscode, String depcode) {
        return departmentRepository.getDepartmentByHoscodeAndDepcode(hoscode, depcode);
    }
}
